package top.ucat.x.system.service.management;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.ucat.box.starter.mybatis.plus.base.service.BaseCrudServiceImpl;
import top.ucat.x.system.dao.api.SysRoleDao;
import top.ucat.x.system.entity.SysRole;
import top.ucat.x.system.entity.SysRoleGroup;
import top.ucat.x.system.entity.beans.role.RoleTreeVo;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Auther: Jun
 * @Date: 2020/4/21 17:43
 * @Description:
 */
@Service
public class SysRoleServiceImpl extends BaseCrudServiceImpl<SysRole> implements SysRoleService {

    @Autowired
    private SysRoleGroupService sysRoleGroupService;

    @Autowired
    private SysRoleDao sysRoleDao;

    @Override
    public List<SysRole> getAllRole() {
        return sysRoleDao.list();
    }

    @Override
    public List<RoleTreeVo> getRoleTrees() {
        List<SysRoleGroup> groups = sysRoleGroupService.getAllGroup();
        List<SysRole> roles = this.getAllRole();
        Map<String, List<RoleTreeVo>> roleMap = roles.stream()
                .map(r -> {
                    RoleTreeVo roleTreeVo = new RoleTreeVo();
                    roleTreeVo.setId(r.getId());
                    roleTreeVo.setRoleGroupId(r.getRoleGroupId());
                    roleTreeVo.setLabel(r.getRoleName());
                    return roleTreeVo;
                })
                .collect(Collectors.groupingBy(RoleTreeVo::getRoleGroupId));
        List<RoleTreeVo> trees = groups.stream().map(g -> {
            RoleTreeVo roleTreeVo = new RoleTreeVo();
            roleTreeVo.setId(g.getId());
            roleTreeVo.setLabel(g.getGroupName());
            if (roleMap.containsKey(g.getId())) {
                roleTreeVo.setChildren(roleMap.get(g.getId()));
            }
            return roleTreeVo;
        }).collect(Collectors.toList());
        return trees;
    }

    @Override
    public List<SysRole> getRolesByIds(Collection ids) {
        if (ids.isEmpty()) {
            return new ArrayList<>();
        }
        List<SysRole> list = sysRoleDao.list(sysRoleDao.getWrapper().lambda().in(SysRole::getId, ids));
        return list;
    }
}
